package com.joy.practice.client;

import com.joy.common.order.OrderOperation;
import com.joy.practice.client.codec.OperationToMessageEncoder;
import com.joy.practice.client.codec.OrderFrameDecoder;
import com.joy.practice.client.codec.OrderFrameEncoder;
import com.joy.practice.client.codec.OrderProtocolDecoder;
import com.joy.practice.client.codec.OrderProtocolEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * 使用OperationToMessageEncoder将Operation转换成一个requestMessage
 */
public class ClientV2 {

    public static void main(String[] args){
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new OrderFrameDecoder())
                                    .addLast(new OrderFrameEncoder())
                                    .addLast(new OrderProtocolEncoder())
                                    .addLast(new OrderProtocolDecoder())
                                    .addLast(new OperationToMessageEncoder())
                                    .addLast(new LoggingHandler(LogLevel.INFO));
                        }
                    });
            ChannelFuture future = bootstrap.connect("127.0.0.1", 8090).sync();
            future.channel().writeAndFlush(new OrderOperation(1002, "malingshu"));
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }

}
